package work.linruchang.util.business.crawl.WeChatReading;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.List;

/**
 * 微信读书的书籍信息
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/09/04
 * @since 1.8
 **/
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class WeChatReadingBookInfo implements Serializable {

    /**
     * 作者
     */
    String author;

    /**
     * 书名
     */
    String name;

    /**
     * 章节列表
     */
    List<ChapterInfo> chapterInfos = CollUtil.newArrayList();

    private WeChatReadingBookInfo addChapterInfo(Integer chapterId, String chapterName) {
        chapterInfos.add(ChapterInfo.builder().name(chapterName).id(chapterId).build());
        return this;
    }

    public WeChatReadingBookInfo addChapterInfos(List<String> chapterNames) {
        CollUtil.forEach(CollUtil.emptyIfNull(chapterNames), (chapterName, index) -> {
            addChapterInfo(index + 1, chapterName);
        });
        return this;
    }

    /**
     * 设置章节所在的链接
     *
     * @param chapterName
     * @param chapterHyperlink
     * @return
     */
    public WeChatReadingBookInfo setChapterLink(String chapterName, String chapterHyperlink) {
        if (StrUtil.isAllNotBlank(chapterName, chapterHyperlink)) {
            chapterInfos.stream()
                    .filter(chapterInfo -> StrUtil.equals(chapterInfo.getName(), chapterName))
                    .findFirst()
                    .ifPresent(chapterInfo -> chapterInfo.setHyperlink(chapterHyperlink));
        }
        return this;
    }

    public ChapterInfo getChapterInfoByName(String chapterName) {
        return chapterInfos.stream()
                .filter(chapterInfo -> StrUtil.equals(chapterInfo.getName(), chapterName))
                .findFirst()
                .orElse(null);
    }


    /**
     * 获取对应章节的{@link ChapterInfo#id}属性字段值
     *
     * @param chapterName
     * @return 找不到则返回-1
     */
    public int getChapterId(String chapterName) {
        return chapterInfos.stream()
                .filter(chapterInfo -> StrUtil.equals(chapterInfo.getName(), chapterName))
                .findFirst()
                .map(ChapterInfo::getId)
                .orElse(-1);
    }


}
